#include <STC/STC89C5xRC.H>

// 自订数据类型
typedef unsigned char uchar;
typedef unsigned int uint;

sbit RS = P35;
sbit RW = P36;
sbit ENABLE = P34;

/**
 * LCD模块忙时等候回圈
 */
void busy_hook()
{
	uchar busy;

	P0 = 0xff;
	RS = 0;
	RW = 1;

	do
	{
		ENABLE = 1;
		busy = P0;
		ENABLE = 0;
	} while (busy & 0x80);
}

/**
 * 写一字节命令
 */
void send_cmd(uchar cmd)
{
	busy_hook();

	RS = 0;
	RW = 0;

	P0 = cmd;

	ENABLE = 1;
	ENABLE = 0;
}

/**
 * 写一字节数据
 */
void send_data(uchar data)
{
	busy_hook();

	RS = 1;
	RW = 0;

	P0 = data;

	ENABLE = 1;
	ENABLE = 0;
}

void lcd_init()
{
	ENABLE = 0;

	send_cmd(0x38); // 16 * 2
	send_cmd(0x0f); // 启用：显示光标，且光标闪烁
	send_cmd(0x06); // 光标（地址指针）移动方式
	send_cmd(0x01); // 清屏
}

/**
 * LCD1602
 * 显示「12345」
 */
void main()
{
	uchar i = 1; // TODO

	lcd_init();

	send_cmd(0x80 | 0x06); // 设定光标

	for (uchar i = 1; i < 6; i++)
	{
		send_data('0' + i);
	}

	while (1)
		;
}
